﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class SectorSort : MonoBehaviour
{
    public bool isClick = false;
    
    public float zRotateUnit = 3f;
    public float xOffsetUnit = 150f;
    public float yOffsetUnit = 8f;

    private void Update()
    {
        if (isClick)
        {
            SortCards();
            isClick = false;
        }
    }

    public void SortCards()
    {
        var childCount = this.gameObject.transform.childCount;

        if (childCount <= 0)
        {
            return;
        }
        
        int middle = childCount / 2;

        for (int i = 0; i < this.gameObject.transform.childCount; i++)
        {
            var cardInstance = this.gameObject.transform.GetChild(i).gameObject;
            cardInstance.transform.rotation = Quaternion.identity;
            
            SetChildCardPosition(cardInstance, this.transform.position);
            Vector3 newPos = cardInstance.transform.position;
            
            if (i == middle)
            {
                newPos.y -= .1f;
                cardInstance.transform.position = newPos;
                continue;
            }
            
            cardInstance.transform.rotation = Quaternion.Euler(0f, 0f, -(i - middle) * zRotateUnit);
//
            newPos.x += (i - middle) * xOffsetUnit;
//            
            newPos.y -= Mathf.Abs((i - middle)) * yOffsetUnit;
//            newPos.y -= Mathf.Abs((i - middle)) * 15f;
            
            cardInstance.transform.position = newPos;
        }
    }

    private void SetChildCardPosition(GameObject cardInstance, Vector3 newPos)
    {
        cardInstance.transform.position = newPos;
    }
}
